package com.platform.system.controller.menu;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.platform.common.annotations.ResponseResult;
import com.platform.common.bean.Result;
import com.platform.common.controller.BaseController;
import com.platform.system.entity.SysMenu;
import com.platform.system.service.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * describe:菜单Api接口
 *
 * @author rainly
 * @date 2019/12/08
 * @time 7:08 下午
 */
@Api(value = "菜单controller", tags = {"菜单操作接口"})
@RestController
@ResponseResult
@RequestMapping(value = "/system/menu")
public class MenuApiController extends BaseController<SysMenu> {

    @Resource
    private SysMenuService sysMenuService;

    @ApiOperation(value = "根据id查询菜单树", notes = "根据id查询菜单树，从叶节点追溯到根节点", httpMethod = "GET")
    @GetMapping(value = "/menuTree/{menuId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object menuTreeReview(@ApiParam(name = "menuId", value = "传入菜单id", required = true)@PathVariable String menuId){
        SysMenu sysMenu = sysMenuService.getById(menuId);
        String parentIds = sysMenu.getParentIds();
        List<String> parenIdList = Arrays.asList(parentIds.split(","));
        List<SysMenu> sysMenuList = new ArrayList<>(parenIdList.size()+1);
        for (String parentId : parenIdList) {
            sysMenuList.add(sysMenuService.getById(parentId));
        }
        sysMenuList.add(sysMenu);
        return sysMenuList;
    }

    @ApiOperation(value = "根据id查询菜单树", notes = "根据id查询菜单树，从根节点迭代到叶节点", httpMethod = "GET")
    @GetMapping(value = "/menuTree", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object menuTreeIterate(@RequestParam String parentId){
        return sysMenuService.selectMenuTree(parentId);
    }

    /**
     * 菜单列表
     *
     * @param pageNum  当前分页
     * @param pageSize 当前分页数量
     * @return 列表
     */
    @ApiOperation(value = "菜单列表", tags = {"菜单列表"}, notes = "必须传入page和limit", httpMethod = "GET" )
    @GetMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object getMenuList(@ApiParam(name = "page", value = "当前分页", required = true) Integer pageNum,
                              @ApiParam(name = "limit", value = "当前分页数量", required = true) Integer pageSize) {
        if (null == pageNum || pageNum == 0) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize == 0) {
            pageSize = this.pageSize;
        }
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        String parentId = this.getRequest().getParameter("parentId");
        if (StringUtils.isNotBlank(parentId)) {
            queryWrapper.eq("parentId", parentId);
        }else {
            queryWrapper.eq("parentId", "0");
        }
        return PageHelper.startPage(pageNum, pageSize, true).doSelectPage(() -> sysMenuService.list(queryWrapper)).toPageInfo();
    }

    /**
     * 新增菜单
     *
     * @param sysMenu 新增菜单
     * @return 保存结果
     */
    @ApiOperation(value = "新增菜单", notes = "新增菜单", httpMethod = "POST")
    @PostMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object postMenu(@ApiParam(name = "菜单对象", value = "传入json格式", required = true) @ModelAttribute @Valid SysMenu sysMenu, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<String> errorMessageList = bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
            return Result.failure(errorMessageList);
        } else {
            return sysMenuService.save(sysMenu);
        }
    }

    /**
     * 修改菜单
     *
     * @param sysMenu 菜单对象
     * @return 修改结果
     */
    @ApiOperation(value = "修改角色", notes = "修改角色", httpMethod = "PUT")
    @PutMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object putMenuById(@ApiParam(name = "角色对象", value = "传入json格式", required = true) @ModelAttribute @Valid SysMenu sysMenu, BindingResult bingdingResult) {
        if (bingdingResult.hasErrors()) {
            List<String> errorMessageList = bingdingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
            return Result.failure(errorMessageList);
        } else {
            return sysMenuService.updateById(sysMenu);
        }
    }

    /**
     * 修改菜单
     *
     * @param sysMenu 菜单对象
     * @return 修改结果
     */
    @ApiOperation(value = "修改属性", notes = "修改属性", httpMethod = "PATCH")
    @PatchMapping(value = "/")
    public Object patchMenuByid(@ApiParam(name = "param", value = "传入json格式的角色属性", required = true) @RequestBody SysMenu sysMenu) {
        if (StringUtils.isNotBlank(sysMenu.getMenuId())) {
            return sysMenuService.updateById(sysMenu);
        } else {
            return "id不能为空";
        }
    }

    /**
     * 根据id查询
     *
     * @param menuid 菜单id
     * @return 菜单对象
     */
    @ApiOperation(value = "根据id查询角色组", notes = "根据id查询角色组", httpMethod = "GET")
    @GetMapping(value = "/{menuid}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object getMenuById(@PathVariable String menuid) {
        return Optional.ofNullable(sysMenuService.getById(menuid));
    }

    /**
     * 根据id删除
     *
     * @param menuid 菜单id
     * @return 是否删除成功
     */
    @ApiOperation(value = "根据id删除角色组", notes = "根据id删除角色组", httpMethod = "DELETE")
    @DeleteMapping(value = "/{menuid}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object delMenuById(@PathVariable String menuid) {
        return sysMenuService.removeById(menuid);
    }

    /**
     * 批量删除
     *
     * @param ids list<Stirng> ids list数组
     * @return 是否删除成功
     */
    @DeleteMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object delMenuByIds(@RequestBody List<String> ids) {
        return sysMenuService.removeByIds(ids);
    }
}
